import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@views/Home'
import { isLogin } from '@utils'
Vue.use(VueRouter)

const routes = [
  {
    path: '/home',
    name: '首页',
    component: Home,
    meta: {
      needLogin: false,
      keepAlive: true
    }
  },
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/cate',
    name: '分类',
    meta: {
      needLogin: false
    },
    component: () => import('@views/Cate')
  },
  {
    path: '/cart',
    name: '购物车',
    component: () => import('@views/Cart'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/user',
    name: '个人中心',
    component: () => import('@views/User'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/itemList/:cateId',
    name: '商品列表',
    component: () => import('@views/ItemList')
  },
  {
    path: '/detail',
    name: '商品详情',
    component: () => import('@views/Detail'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/login',
    name: '登录',
    component: () => import('@views/Login'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/order',
    name: '订单',
    component: () => import('@views/Order'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/contactLists',
    name: '所有联系人',
    component: () => import('@views/ContactLists'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/contactEdit',
    name: '编辑联系人',
    component: () => import('@views/ContactEdit'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/contactAdd',
    name: '增加联系人',
    component: () => import('@views/ContactAdd'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/search',
    name: '搜索页',
    component: () => import('@views/Search'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/searchResult',
    name: '搜索页',
    component: () => import('@views/SearchResult'),
    meta: {
      needLogin: false
    }
  }
]

const router = new VueRouter({
  routes,
  scrollBehavior: (to, from, savedPosition) => {
    if (savedPosition) {
      return savedPosition
    } else {
      return {
        x: 0,
        y: 0
      }
    }
  }
})
// 增加路由前置守卫
router.beforeEach((to, from, next) => {
  // 判断当前路由是否需要登录
  if (to.meta.needLogin) {
    // 需要登录
    if (isLogin()) {
      // 登录了
      next()
    } else {
      next({
        path: '/login',
        query: {
          from: to.path
        }
      })
    }
  } else {
    // 不需要登录
    next()
  }
})
export default router
